#include "reader.h"

#include <QDebug>

Reader::Reader():Process()
{
    name = "Reader";
}

Reader::~Reader()
{
}

void Reader::Run()
{
    LogManager::getSingleton().Message("Reader", "step "+LogManager::getSingleton().toStr(currentStep));
    switch(currentStep){
    case 0:{
        ResourceAllocator::getSingleton().askForResource("ProgramLoadingBuffer",id);
    }
    break;
    case 1:{
        Resource* nx = usingResourceList.at(usingResourceList.size()-1);
        ElementsBase* bb = nx->getElement();
        String path = bb->front();
        std::ifstream infile(path);

        if(!infile)
        {
            qDebug() << "gg @ Reader::Run1";
            return;
        }

        String line;
        fileString = "";

        while (std::getline(infile, line))
        {
            std::istringstream iss(line);

            fileString.append(iss.str());

            /*
            int lineSize = line.size();
            if(lineSize != MAX_LINE_LENGTH)
            {
                std::cout << " lines must not be longer than 4 bytes." << std::endl;
                return;
            }
            else
            {
                Word temp;
                temp[0] = line.at(0);
                temp[1] = line.at(1);
                temp[2] = line.at(2);
                temp[3] = line.at(3);

                rOutput->push_back(temp);
            }
            */
        }
        if(fileString.empty()) {
            qDebug() << "gg @ Reader::Run1.2";
            return;
        }

    }
    break;
    case 2:{
         qDebug() << "fr";
         ResourceAllocator::getSingleton().destroyResource(usingResourceList.at(0));
         qDebug() << "ee";
    }
    break;
    case 3:{
        ResourceAllocator::getSingleton().addResource(new ProgramInBuffer(id, fileString));
        currentStep=-1;
    }
    break;
    default:
      qDebug() << "gg Reader";
    }
    currentStep++;
}
